package com.yimixian.app.rest.api;

import com.ta.utdid2.android.utils.StringUtils;
import com.yimixian.app.common.CacheKeys;
import com.yimixian.app.common.SharePreferenceKeys;
import com.yimixian.app.data.DataManager;
import com.yimixian.app.model.Banner;
import com.yimixian.app.model.GoodsItem;
import com.yimixian.app.model.HeadInfo;
import com.yimixian.app.model.HomeAdWindow;
import com.yimixian.app.model.HomeDataBean;
import com.yimixian.app.model.ImageInfo;
import com.yimixian.app.model.LoginBanner;
import com.yimixian.app.model.Material;
import com.yimixian.app.model.SearchKeyResult;
import com.yimixian.app.model.SortGoodsItem;
import com.yimixian.app.model.SortItemBean;
import com.yimixian.app.util.SharedPreferencesHelper;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit.Callback;
import retrofit.client.Response;

/**
 * 获取首页数据接口
 */
public class HomeDataAPI extends YmxBaseAPI<HomeDataBean> {

    public static final String HOMEDATAURL = "/v5/home_page";

    public List<SortGoodsItem> goodsItems;
    public List<GoodsItem> mList;

    public String addressId;
    public String poiId;
    public String longitude;
    public String latitude;
    public String coordSystem;

    public HomeDataAPI(String addressId, Callback<Response> callback) {
        super(callback);
        this.addressId = addressId;
    }

    public HomeDataAPI(String longitude, String latitude, String poiId, String coordSystem,
            Callback<Response> callback) {
        super(callback);
        this.longitude = longitude;
        this.latitude = latitude;
        this.poiId = poiId;
        this.coordSystem = coordSystem;
    }

    @Override
    public String getRelativeURL() {
        return HOMEDATAURL;
    }

    // 通过定位获取信息
    public void getHomeDataByLocated() {
        String token = DataManager.getInstance().get(CacheKeys.TOKEN);
        if (StringUtils.isEmpty(token)) token = "";
        mYmxRestService.getHomeDataByLocated(token, longitude, latitude, poiId, coordSystem, mCallback);
    }

    // 通过addressId获取信息
    public void getHomeDataBySaved() {
        String token = DataManager.getInstance().get(CacheKeys.TOKEN);
        if (StringUtils.isEmpty(token)) token = "";
        mYmxRestService.getHomeDataBySaved(token, addressId, mCallback);
    }

    @Override
    public HomeDataBean parseJson(JSONObject jsonObject) {
        HomeDataBean homeDataBean = null;
        LoginBanner loginBanner = null;
        if (jsonObject != null) {
            homeDataBean = new HomeDataBean();
            loginBanner = new LoginBanner();
            homeDataBean.id = jsonObject.optInt("id");
            homeDataBean.name = jsonObject.optString("name");
            homeDataBean.isActive = jsonObject.optBoolean("is_active");
            homeDataBean.storeNotice = jsonObject.optString("store_notice");
            homeDataBean.deliveryZoneUrl = jsonObject.optString("delivery_zone_url");
            homeDataBean.cannotDeliverText = jsonObject.optString("cannot_deliver_text");
            homeDataBean.regionId = jsonObject.optString("region_id");
            homeDataBean.imageRatio = jsonObject.optDouble("image_ratio");
            JSONObject jObj= jsonObject.optJSONObject("login_page_ad");
            if(null!=jObj){
                loginBanner.ad_id = jObj.optInt("ad_id");
                loginBanner.image = jObj.optString("image");
                loginBanner.url = jObj.optString("url");
                loginBanner.imgRatio= (float)jObj.optDouble("img_ratio");
                SharedPreferencesHelper.saveObject(SharePreferenceKeys.LOGIN_BANNER,loginBanner);
            }else{
                SharedPreferencesHelper.clearStore(SharePreferenceKeys.LOGIN_BANNER);
            }
            if (!homeDataBean.isActive)
                return homeDataBean;

            JSONArray array = jsonObject.optJSONArray("card_list");
            if (array != null) {
                Map<String, Material> maps = new HashMap<>();
                homeDataBean.dataMap = maps;

                for (int i = 0; i < array.length(); i++) {
                    JSONObject object = array.optJSONObject(i);
                    if (object != null) {

                        String type = object.optString("type");
                        JSONArray jsonArray = object.optJSONArray("material");
                        if (!StringUtils.isEmpty(type) && jsonArray != null) {

                            if (ResponseDataTypeAPI.HomeDataType.SLIDES.equals(type)){// 轮播图
                                Material<Banner> material = new Material<>();
                                maps.put(type, material);
                                material.type = type;
                                material.sort = object.optInt("sort");
                                material.mList = new ArrayList<>();
                                for (int j = 0; j < jsonArray.length(); j++) {
                                    JSONObject object1 = jsonArray.optJSONObject(j);
                                    Banner banner = new Banner();
                                    banner.img = object1.optString("image");
                                    banner.introUrl = object1.optString("url");
                                    if (!StringUtils.isEmpty(object1.optString("img_ratio"))){
                                        banner.image_ratio = (float)object1.optDouble("img_ratio");
                                    }
                                    material.mList.add(banner);
                                }
                            }

                            if (ResponseDataTypeAPI.HomeDataType.METROS.equals(type) || // metros
                                    ResponseDataTypeAPI.HomeDataType.BANNERS.equals(type)) {// banners
                                Material<ImageInfo> material = new Material<>();
                                maps.put(type, material);
                                material.type = type;
                                material.sort = object.optInt("sort");
                                material.mList = new ArrayList<>();
                                for (int j = 0; j < jsonArray.length(); j++) {
                                    JSONObject object1 = jsonArray.optJSONObject(j);
                                    ImageInfo imageInfo = new ImageInfo();
                                    imageInfo.title = object1.optString("title");
                                    imageInfo.image = object1.optString("image");
                                    imageInfo.url = object1.optString("url");
                                    if (!StringUtils.isEmpty(object1.optString("img_ratio"))){
                                        imageInfo.image_ratio = (float)object1.optDouble("img_ratio");
                                    }
                                    material.mList.add(imageInfo);
                                }
                            }

                            //滚动头条
                            if (ResponseDataTypeAPI.HomeDataType.SETHEADLINE.equals(type)) {
                                Material<HeadInfo> material = new Material<>();
                                maps.put(type, material);
                                material.type = type;
                                material.sort = object.optInt("sort");
                                material.mList = new ArrayList<>();
                                for (int j = 0; j < jsonArray.length(); j++) {
                                    JSONObject object1 = jsonArray.optJSONObject(j);
                                    HeadInfo headInfo = new HeadInfo();
                                    headInfo.title = object1.optString("title");
                                    headInfo.desc = object1.optString("desc");
                                    headInfo.url = object1.optString("url");
                                    headInfo.type = object1.optString("type");
                                    material.mList.add(headInfo);
                                }
                            }

                            // special_list
                            if (ResponseDataTypeAPI.HomeDataType.SPECIALLIST.equals(type)) {
                                homeDataBean.mList = new ArrayList<>();
                                Material<SortItemBean> material = new Material<>();
                                maps.put(type, material);
                                material.type = type;
                                material.sort = object.optInt("sort");
                                material.mList = new ArrayList<>();
                                for (int j = 0; j < jsonArray.length(); j++) {

                                    JSONObject objectSpecial = jsonArray.optJSONObject(j);
                                    if (objectSpecial != null){
                                        SortItemBean sortItemBean = new SortItemBean();
                                        material.mList.add(sortItemBean);
                                        sortItemBean.id = objectSpecial.optString("id");
                                        sortItemBean.name = objectSpecial.optString("name");
                                        sortItemBean.subTitle = objectSpecial.optString("sub_title");
                                        JSONArray array1 = objectSpecial.optJSONArray("goods");
                                        if (array1 != null){
                                            sortItemBean.mGoodsItems = new ArrayList<>();
                                            for (int l = 0; l < array1.length(); l++){
                                                JSONObject object1 = array1.optJSONObject(l);
                                                GoodsItem goodsItem = new GoodsItem();
                                                goodsItem.id = object1.optInt("id");
                                                goodsItem.name = object1.optString("name");
                                                if (!StringUtils.isEmpty(object1.optString("img_ratio"))){
                                                    goodsItem.imgRatio = object1.optInt("img_ratio");
                                                }
                                                goodsItem.img = object1.optString("img");
                                                goodsItem.promotionImg = object1
                                                        .optString("promotion_img");
                                                goodsItem.descUrl = object1.optString("desc_url");
                                                goodsItem.unitDesc = object1.optString("unit_desc");
                                                goodsItem.saleStatus = object1.optString("sale_status");
                                                goodsItem.unitPrice = object1.optString("unit_price");
                                                goodsItem.stockCount = object1.optString("stock_count");
                                                goodsItem.start_time = object1.optLong("start_time");
                                                goodsItem.unitOldPrice = object1
                                                        .optString("unit_old_price");
                                                goodsItem.shouldBuyCount = object1
                                                        .optInt("should_buy_count");
                                                goodsItem.isBuyingGroup = object1
                                                        .optInt("is_buying_group");
                                                goodsItem.buyingGroupCount = object1
                                                        .optInt("buying_group_count");
                                                goodsItem.buyingGroupPrice = object1
                                                        .optInt("buying_group_price");
                                                goodsItem.countZeroReason = object1.optString("count_zero_reason");
                                                sortItemBean.mGoodsItems.add(goodsItem);
                                            }
                                        }
                                        JSONArray arrayBanner = objectSpecial.optJSONArray("banners");
                                        sortItemBean.mBannerItems = new ArrayList<>();
                                        if(arrayBanner != null){
                                            for (int m = 0; m < arrayBanner.length(); m++) {
                                                JSONObject bannerObject = arrayBanner.optJSONObject(m);
                                                Banner banner = new Banner();
                                                banner.img = bannerObject.optString("image");
                                                banner.introUrl = bannerObject.optString("url");
                                                if (!StringUtils.isEmpty(bannerObject.optString("img_ratio"))){
                                                    banner.image_ratio = (float) bannerObject.optDouble("img_ratio");
                                                }
                                                sortItemBean.mBannerItems.add(banner);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            JSONObject object = jsonObject.optJSONObject("window_ad");
            if (object != null){
                HomeAdWindow mHomeAdWindow = new HomeAdWindow();
                mHomeAdWindow.adId = object.optString("ad_id");
                mHomeAdWindow.image = object.optString("image");
                mHomeAdWindow.url = object.optString("url");
                homeDataBean.mHomeAdWindow = mHomeAdWindow;
            }
        }


        translateArray(homeDataBean);
        return homeDataBean;
    }


    public List<SortGoodsItem> translateArray(HomeDataBean homeDataBean){
        goodsItems = new ArrayList<>();

        if (homeDataBean == null) return goodsItems;
        Material<SortItemBean> sortItemBeanMaterial = homeDataBean.dataMap.
                get(ResponseDataTypeAPI.HomeDataType.SPECIALLIST);
        if (sortItemBeanMaterial == null || sortItemBeanMaterial.mList == null) return goodsItems;
        List<SortItemBean> list = sortItemBeanMaterial.mList;
        mList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++){
            SortItemBean bean = list.get(i);

            if (bean != null && bean.mGoodsItems != null){
                List<GoodsItem> items = bean.mGoodsItems;
                int size = items.size();
                //添加section
                if (size > 0){
                    SortGoodsItem sortGoodsItem = new SortGoodsItem(SortGoodsItem.SECTION);
                    if (!StringUtils.isEmpty(bean.id)) sortGoodsItem.id = bean.id;
                    sortGoodsItem.name = bean.name;
                    goodsItems.add(sortGoodsItem);
                }
//                //添加section后面的item
//                for (int j = 0; j < size; j++){
//                    SortGoodsItem sortGoodsItem = new SortGoodsItem(SortGoodsItem.ITEM);
//                    if (2 * j <= size - 1) {
//                        sortGoodsItem.leftGoodsItem = items.get(2 * j);
//                        mList.add(items.get(2 * j));
//                        if (2 * j + 1 <= size - 1){
//                            sortGoodsItem.RightGoodsItem = items.get(2 * j + 1);
//                            mList.add(items.get(2 * j + 1));
//                        }
//                        goodsItems.add(sortGoodsItem);
//                    }
//                }


//                //添加section后面的item
//                for (int j = 0; j < size; j++){
//                    SortGoodsItem sortGoodsItem = null;
//                    if(j % 3 == 0){
//                        sortGoodsItem = new SortGoodsItem(SortGoodsItem.ITEM);
//                        goodsItems.add(sortGoodsItem);
//                        sortGoodsItem.leftGoodsItem = items.get(j);
//                    }else{
//                        sortGoodsItem = goodsItems.get(goodsItems.size() - 1);
//                        if(j % 3 == 1){
//                            sortGoodsItem.RightGoodsItem = items.get(j);
//                        }else if(j % 3 == 2){
//                            sortGoodsItem.thirdGoodsItem = items.get(j);
//                        }
//                    }
//                    sortGoodsItem.mBannerItems = bean.mBannerItems;
//                    sortGoodsItem.id = bean.id;
//                    mList.add(items.get(j));
//
//                }

                //添加section后面的item
                SortGoodsItem sortGoodsItem = new SortGoodsItem(SortGoodsItem.ITEM);
                sortGoodsItem.rowData = items;
                goodsItems.add(sortGoodsItem);
                sortGoodsItem.mBannerItems = bean.mBannerItems;
                sortGoodsItem.id = bean.id;
                mList.addAll(items);
            }

        }

        return goodsItems;
    }
}
